import glfw
import glm
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
import ctypes
import time


def framebuffer_size_callback(window, width, height):
    glViewport(0, 0, width, height)

def processInput(window):
    if glfw.get_key(window, glfw.KEY_ESCAPE) == glfw.PRESS:
        glfw.set_window_should_close(window, True)

if __name__ == "__main__":
    if not glfw.init():
        print("Failed to initialize GLFW")
        raise Exception("Failed to initialize GLFW")
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window = glfw.create_window(800, 600, "Hello World", None, None)
    if not window:
        print("Failed to create GLFW window")
        glfw.terminate()
        raise Exception("Failed to create GLFW window")
    
    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    vertices = np.array([
            0.5, 0.5, 0.0,
            0.5, -0.5, 0.0,
            0, 0, 0,
            -0.5, -0.5, 0.0,
            -0.5,  0.5, 0.0
        ], dtype=np.float32)
    
    face = np.array([
            0, 4, 2,
            1, 3, 2
        ], dtype=np.uint32)


    vertexShaderSource = '''
        #version 330 core
        layout (location = 0) in vec3 aPos; // 位置变量的属性位置值为 0 
        uniform mat4 transform;
        void main()
        {
            gl_Position = transform * vec4(aPos.x, aPos.y, aPos.z, 1.0);
        }
        '''

    vertexShader = glCreateShader(GL_VERTEX_SHADER)
    glShaderSource(vertexShader, vertexShaderSource)
    glCompileShader(vertexShader)
    if not glGetShaderiv(vertexShader, GL_COMPILE_STATUS):
        print(glGetShaderInfoLog(vertexShader))
        raise Exception("Failed to compile vertex shader")
    
    fragmentShaderSource = '''
        #version 330 core
        out vec4 FragColor;
        void main()
        {
            FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
        }
    '''

    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER)
    glShaderSource(fragmentShader, fragmentShaderSource)
    glCompileShader(fragmentShader)

    shaderProgram = glCreateProgram()
    glAttachShader(shaderProgram, vertexShader)
    glAttachShader(shaderProgram, fragmentShader)
    glLinkProgram(shaderProgram)
    if not glGetProgramiv(shaderProgram, GL_LINK_STATUS):
        print(glGetProgramInfoLog(shaderProgram))
        raise Exception("Failed to link shader program")
    
    glDeleteShader(vertexShader)
    glDeleteShader(fragmentShader)

    # 创建带有缓冲对象的 VBO, VAO, EBO 对象
    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(1)
    EBO = glGenBuffers(1)

    glBindVertexArray(VAO)

    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, face.nbytes, face, GL_STATIC_DRAW)

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * vertices.itemsize, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    glBindBuffer(GL_ARRAY_BUFFER, 0)

    glBindVertexArray(0)

    angle = 0
    while not glfw.window_should_close(window):
        glfw.poll_events()
        processInput(window)

        glClearColor(0.2, 0.3, 0.3, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        glUseProgram(shaderProgram)

        # 创建旋转矩阵
        transform = glm.rotate(glm.mat4(1.0), glm.radians(angle), glm.vec3(0, 0, 1))  # z轴旋转90度

        # 获取Uniform变量的地址
        transformLoc = glGetUniformLocation(shaderProgram, "transform")
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, np.array(transform).tobytes())
        
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)
        

        glfw.swap_buffers(window)

        time.sleep(0.01)
        angle += 1

    glDeleteBuffers(1, [VBO])
    glDeleteBuffers(1, [EBO])
    glDeleteVertexArrays(1, [VAO])
    glfw.terminate()

    
    print('ok')